package com.example.lin.api;

import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.SSLContext;
import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

/**
 * @className: EmsV2
 * @description:
 * @author: Lin.Gu
 * @date: 2025/2/21
 */
public class EmsV2 {

    public static void main(String[] args) throws Exception {
        // 创建一个信任所有证书的SSLContext
        TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
        SSLContext sslContext = SSLContexts.custom()
                .loadTrustMaterial(null, acceptingTrustStrategy)
                .build();

        // 创建忽略主机名验证的SSLConnectionSocketFactory
        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

        // 创建HttpClient
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(csf)
                .build();

        // 使用HttpClient创建RequestFactory
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);

        // 创建RestTemplate并设置RequestFactory
        RestTemplate restTemplate = new RestTemplate(requestFactory);


        String url = "https://211.156.197.233/jdpt-order-pus-web/interface/receive/undoOrder";
        String salt = "19dd6c1cec504ac854645f352eb03209";

        String orderNo = "ZYZWZX202203021021002";

        String sign = hmacMd5Hex(salt, orderNo);
        System.out.println("sign: " + sign);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("orderNo", orderNo);
        map.put("sign", sign);
        map.put("authorization", "sccdzw1638933341");
        map.put("cancelCode", 16);

        String response = restTemplate.postForObject(url, map, String.class);
        System.out.println("response: " + response);


    }

    /**
     * 使用 HMAC - MD5 算法对数据进行签名，并返回十六进制字符串结果
     *
     * @param key  密钥
     * @param data 要签名的数据
     * @return 签名后的十六进制字符串
     */
    public static String hmacMd5Hex(String key, String data) {
        try {
            // 获取 HMAC - MD5 算法的 Mac 实例
            Mac mac = Mac.getInstance("HmacMD5");
            // 创建密钥规范
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacMD5");
            // 初始化 Mac 实例
            mac.init(secretKeySpec);
            // 进行签名计算
            byte[] hmacBytes = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
            // 将字节数组转换为十六进制字符串
            return bytesToHex(hmacBytes);
        } catch (Exception e) {
            // 处理异常
            throw new RuntimeException("HMAC - MD5 计算出错", e);
        }
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param bytes 字节数组
     * @return 十六进制字符串
     */
    private static String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }

}
